package org.abettor.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URL;

/**
 * 通过IO流传递（序列化与反序列化）对象的类
 * @author <a href="http://www.abettor.org/" target="_blank">abettor</a>
 *
 */
public class ObjectTransporter
{
	//	禁止直接实例化
	protected ObjectTransporter()
	{
	}

	/**
	 * 将obj序列化并写入流out中
	 * @param obj 要传递的对象实例
	 * @param out 已经存在并打开的输出流对象
	 * @throws IOException
	 */
	public static void writeObject(Serializable obj, OutputStream out) throws IOException
	{
		ObjectOutputStream oos = new ObjectOutputStream(out);
		oos.writeObject(obj);
	}

	/**
	 * 从流in中获取一个对象实例
	 * @param in 已经存在并打开的输入流对象
	 * @return 如果成功的话，返回一个对象实例
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static Serializable readObject(InputStream in) throws IOException, ClassNotFoundException
	{
		ObjectInputStream ois = new ObjectInputStream(in);
		return (Serializable) ois.readObject();
	}

	/**
	 * 从流url制定的地址获取一个对象实例
	 * @param url 网络资源对象
	 * @return 如果成功的话，返回一个对象实例
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static Serializable httpReadObject(URL url) throws IOException, ClassNotFoundException
	{
		InputStream is = url.openStream();
		Serializable obj = readObject(is);
		is.close();
		return obj;
	}

	/**
	 * 从流url制定的地址获取一个对象实例
	 * @param url 网络资源字符串
	 * @return 如果成功的话，返回一个对象实例
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static Serializable httpReadObject(String urlString) throws IOException, ClassNotFoundException
	{
		URL url = new URL(urlString);
		InputStream is = url.openStream();
		Serializable obj = readObject(is);
		is.close();
		return obj;
	}
}
